package ee.serge.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gwt.core.client.GWT;

/**
 * For storing data of url in a CGI-like way.
 */
public class URLData {

   private Map<String, String> dataMap;
   
   public URLData() {
      dataMap = new HashMap<String, String>();
      dataMap.put(null, "");
   }
   
   public URLData(String href) {
      parseHref(href);
   }
   
   public void add(String key, String value) {
      dataMap.put(key, value);
   }
   
   public void add(String key, long value) {
      dataMap.put(key, String.valueOf(value));
   }
   
   public void setName(String name) {
      dataMap.put(null, name);
   }
   
   public String getHref() {
      if (dataMap.size() <= 0) return "";
      //buffer.append("!#");//FIXME hash peab olema formaadis !#
      String name = dataMap.get(null);
      dataMap.remove(null);
      
      StringBuffer buffer = new StringBuffer();
      buffer.append(name);
      if (dataMap.size() > 0) {
         buffer.append("?");
      }
      Iterator<Entry<String, String>> it = dataMap.entrySet().iterator();
      while (it.hasNext()) {
         Entry<String, String> entry = it.next();
         if (entry.getKey() != null) {
            buffer.append(entry.getKey());
            buffer.append("=");
            buffer.append(entry.getValue());
         }
         if (it.hasNext()) buffer.append("&");
      }
      dataMap.put(null, name);
      return buffer.toString();
   }
   
   public String get(String key) {
      return dataMap.get(key);
   }
   
   public String getName() {
      return dataMap.get(null);
   }
   
   private void parseHref(String href) {
      dataMap = new HashMap<String, String>();
      try {
         String[] pairs;
         pairs = href.split("[?&]");
         dataMap.put(null, pairs[0]);
         for (int i = 1; i < pairs.length; i++) {
         //for (String pair : pairs) {
            String[] keyValuePair = pairs[i].split("=");
            if (keyValuePair.length == 2) {
               dataMap.put(keyValuePair[0], keyValuePair[1]);
            } /*else {
               dataMap.put(null, pairs[i]);
            }*/
         }
      } catch (Exception e) {
         GWT.log("Parsing href failed (" + href + "). " + e.getMessage());
         //Do nothing.
      }
   }

   public Map<String, String> getDataMap() {
      return dataMap;
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      URLData other = (URLData) obj;
      if (dataMap == null) {
         if (other.dataMap != null)
            return false;
      } else if (getHref().equals(other.getHref()))
         return true;
      return false;
   }
   
}
